package com.hangman;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class XMLHandler extends DefaultHandler {
	private XMLReader reader;
	private ArrayList<Category> categories;
	private String language;

	public XMLHandler(XMLReader reader, String chosenLanguage) {
		this.reader = reader;
		this.categories = new ArrayList<Category>();
		this.language = chosenLanguage;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (localName.equals("language")) {
			if (attributes.getValue("name").equals(language)) {
				reader.setContentHandler(new CategoryHandler(reader, this));
			}
		}
	}

	public ArrayList<Category> getCategories() {
		return categories;
	}

	class CategoryHandler extends DefaultHandler {

		private XMLReader reader;
		private XMLHandler parent;

		public CategoryHandler(XMLReader reader, XMLHandler parent) {
			this.reader = reader;
			this.parent = parent;
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {

			if (localName.equals("category")) {
				categories.add(new Category(attributes.getValue("name")));
				reader.setContentHandler(new TaskHandler(reader, this));			
			}
		}

		public void endElement(String uri, String localName, String name)
				throws SAXException {
			if (localName.equals("category")) {
				//keep going
			}
			else reader.setContentHandler(parent);
		}
	}

	class TaskHandler extends DefaultHandler {
		private XMLReader reader;
		private CategoryHandler parent;

		private StringBuilder content;

		public TaskHandler(XMLReader reader, CategoryHandler parent) {
			this.reader = reader;
			this.parent = parent;
			this.content = new StringBuilder();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equals("word")) {
				content.setLength(0);
			}
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			content.append(ch, start, length);
		}

		public void endElement(String uri, String localName, String name)
				throws SAXException {
			if (localName.equals("word")) {
				
				categories.get(categories.size()-1).addTask(
						new Task(content.toString()));
			}			
			else reader.setContentHandler(parent);			
		}
	}
}
